﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ZBJF.Warranty.Common.Common
{
    public class ReflectHelper<T1,T2> where T1 : class,new() where T2:class,new()
    {
        /// <summary>
        /// 将View映射的模型转换赋值（克隆）给数据库获取到的实体
        /// </summary>
        /// <param name="t1"></param>
        /// <param name="t2"></param>
        /// <returns></returns>
        public static T2 CloneT1ToT2(T1 t1, T2 t2)
        {
            PropertyInfo[] p1 = t1.GetType().GetProperties();
            PropertyInfo[] p2 = t2.GetType().GetProperties();

            foreach (var item in p1)
            {
                foreach (var itme2 in p2)
                {
                    if (item.Name == itme2.Name && item.PropertyType == itme2.PropertyType)
                    {
                        Object obj = item.GetValue(t1, null);
                        if (obj != null)
                        {
                            DateTime datetime;
                            var time = DateTime.TryParse(obj.ToString(), out datetime);
                            if (!time || (datetime > DateTime.MinValue)) //如果是时间类型，必须大于最小的时间才赋值
                            {
                                itme2.SetValue(t2, obj, null);
                            }
                        }
                        else
                        {
                            if (item.PropertyType == typeof (string)&&item.Name!="CreateBy")//如果是字符串，也赋值
                            {
                                itme2.SetValue(t2, string.Empty, null);
                            }
                        }
                    }
                }
            }
            return t2;
        }
    }
}
